<?php

namespace app\cash\controller\table;

use app\BaseController;
use app\beautiful\model\LevelModel;
use app\beautiful\model\member\MemberBalanceModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\PartnerModel;
use app\beautiful\model\setting\RegionModel;
use app\beautiful\model\setting\TableNumberModel;
use app\cash\model\CartDetailModel;
use app\cash\model\CartModel;
use app\cash\model\CashJointTableModel;
use app\cash\model\CashSettleInfoModel;
use app\cash\model\OpenTableModel;
use app\common\model\account\ShopAccountModel;
use app\stores\model\member\MemberLevelModel;
use app\stores\model\order\GoodsOrderModel;
use think\facade\Db;

class Table extends BaseController{
    /**
     * 区域列表
     */
    public function regionList(){
        $limit=$this->request->limit;
        $page=$this->request->page;
        $where['shop_id'] = $this->request->shopId;
        $where['is_effect'] = 1;
        $where['parent_id'] = 0;
        $order = ['sort'=>'desc'];
        $list = RegionModel::list($where,$order,$page,$limit);
        return $this->success($list);
    }
    /**
     * 桌号列表
     */
    public function tableList(){
        $region_id = $this->request->param('region_id');
        $name = $this->request->param('name');
        $type = $this->request->param('type/d',0);//0全部1空闲2占用
        $status = $this->request->param('status/d',0);//0正常1已开台并未占用
        $limit=$this->request->limit;
        $page=$this->request->page;
        if($type>0){
            //占用
            $table_number_ids = OpenTableModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'status'=>0])->column('table_number_id');
            $where['type'] = $type;
            $where['open_table_number_ids'] = $table_number_ids;
        }
        if($status==1){
            $master_table_number_ids = CashJointTableModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'status'=>0])->column('master_table_number_id');
            $table_number_ids = CashJointTableModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'status'=>0])->column('table_number_id');
            $not_table_number_ids = array_merge($master_table_number_ids,$table_number_ids);
            $where['not_table_number_ids'] = $not_table_number_ids;
        }
        $where['shop_id'] = $this->request->shopId;
        $where['region_id'] = $region_id;
        $where['is_effect'] = 1;
        if($name) $where['name'] = $name;
        $order = ['add_time'=>'desc'];
        $list = TableNumberModel::list($where,$order,$page,$limit);
        //占用桌数
        $t_where['shop_id'] = $this->request->shopId;
        if($region_id>0) $t_where['region_id'] = $region_id;
        $t_where['is_effect'] = 1;
        $t_where['is_delete'] = 0;
        $table_number_ids = TableNumberModel::where($t_where)->column('id');
        $ot_where['shop_id'] = $this->request->shopId;
        $ot_where['status'] = 0;
        $ot_where['is_delete'] = 0;
        $list['occupy_count'] = OpenTableModel::where($ot_where)->whereIn('table_number_id',$table_number_ids)->count();
        $list['free_count'] = $list['count'] - $list['occupy_count'];
        return $this->success($list);
    }
    /**
     * 开台
     */
    public function onTable(){
        $table_number_id = $this->request->param('table_number_id/d',0);
        $member_id = $this->request->param('member_id/d',0);
        $is_fit = $this->request->param('is_fit/d',0);
        $dinner_num = $this->request->param('dinner_num/d',0);
        $remarks = $this->request->param('remarks');

        if($is_fit<1 && $member_id<1) return $this->error('客户信息不正确');
        if($table_number_id<1) return $this->error('请选择桌台');
        if($dinner_num<1) return $this->error('就选择就餐人数');

        $table = TableNumberModel::info(['shop_id'=>$this->request->shopId,'is_effect'=>1,'id'=>$table_number_id]);
        if(empty($table)) return $this->error('桌台不存在');
        $ot = OpenTableModel::getById(['shop_id'=>$this->request->shopId,'table_number_id'=>$table_number_id,'status'=>0]);
        if($ot) return $this->error('桌台已被占用');

        if($member_id>0){
            $member = MemberModel::where(['member_id'=>$member_id])->find();
            if(empty($member)) return $this->error('客户不存在');
        }
        $data['shop_id'] = $this->request->shopId;
        $data['table_number_id'] = $table_number_id;
        $data['member_id'] = $member_id;
        $data['is_fit'] = $is_fit;
        $data['dinner_num'] = $dinner_num;
        $data['remarks'] = $remarks;
        $data['add_ip'] = request()->ip();
        $id = OpenTableModel::insertGetId($data);
        if($id){
            $open_table_info = OpenTableModel::getById(['open_table_id'=>$id]);
            $s_data['data'] = $open_table_info;
            $s_data['type'] = 'open_table';
            pushWebsocket($this->request->shopId,$this->request->accountId,$s_data);

        }
        $return['open_table_id'] = $id;
        $return['member_id'] = $member_id;
        $return['is_fit'] = $is_fit;
        return $this->success($return);
    }
    /**
     *开台信息
     */
    public function tableInfo(){
        $open_table_id = $this->request->param('open_table_id/d',0);
        $ot = OpenTableModel::getById(['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_id],'o.*,t.name as table_name,r.name as region_name');
        if(empty($ot)) return $this->error('开台不存在');
        //联台或并台
        //是否是主桌台
        $master = CashJointTableModel::info(['shop_id'=>$this->request->shopId,'master_open_table_id'=>$open_table_id,'is_delete'=>0,'status'=>0]);
        if($master){
            $table = TableNumberModel::info(['id'=>$ot['table_number_id'],'is_delete'=>0]);
            $list = CashJointTableModel::list(['shop_id'=>$this->request->shopId,'master_open_table_id'=>$open_table_id,'status'=>0,'type'=>$master['type']],'t.open_table_id,n.name');
            $ot['joint_master_table_name'] = $table['name'];
            $ot['joint_type'] = $master['type'];
            $ot['joint_table_list'] = $list;
        }
        //次桌台
        $next = CashJointTableModel::info(['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_id,'is_delete'=>0,'status'=>0]);
        if($next){
            $table = TableNumberModel::info(['id'=>$next['master_table_number_id'],'is_delete'=>0]);
            $list = CashJointTableModel::list(['shop_id'=>$this->request->shopId,'master_open_table_id'=>$next['master_table_number_id'],'status'=>0,'type'=>$next['type']],'t.open_table_id,n.name as table_name');
            $ot['joint_master_table_name'] = $table['name'];
            $ot['joint_type'] = $next['type'];
            $ot['joint_table_list'] = $list;
        }

        $field = 'member_id,nick_name,mobile,face';
        $member = MemberModel::where(['member_id'=>$ot['member_id']])->field($field)->find();
        if($member){
            //股东
            $p_where['shop_id'] = $this->request->shopId;
            $p_where['member_id'] = $member['member_id'];
            $p_where['status'] = 1;
            $p_where['is_delete'] = 0;
            $partner = PartnerModel::info($p_where);
            $member['partner_type'] = $partner?$partner['type']:null;
            //是否是会员
            $mL_model = new MemberLevelModel();
            $ml = $mL_model->getById(['member_id'=>$member['member_id'],'shop_id'=>$this->request->shopId,'is_delete'=>0]);
            $member['is_vip'] = $ml?1:0;
            //等级
            $level_id = getMemberLevel($member['member_id'],$this->request->shopId);
            $level = LevelModel::find($level_id);
            $member['level_name'] = null;
            $member['discount'] = 10;
            if($level){
                $member['level_name'] = $level['name'];
                $member['discount'] = $level['type']==1?$level['discount']:$level['discount_force'];
            }
            //余额
            $member['balance'] = MemberBalanceModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['member_id','=',$member['member_id']],

                    ['valid_bg_time','<=',$this->request->time()]

                ])->sum('remain_balance') ?? 0;

        }
        $ot['member'] = $member;
        return $this->success($ot);
    }
    /**
     *修改开台指定的客户(有结算信息不能修改)
     */
    public function updateTable(){
        $order_id = $this->request->param('order_id/d',0);
        $open_table_id = $this->request->param('open_table_id/d',0);
        $member_id = $this->request->param('member_id/d',0);
        $is_fit = $this->request->param('is_fit/d',-1);
        $data = [];
        if($order_id){
            $order = GoodsOrderModel::where(['order_id'=>$order_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
            if(empty($order)) return $this->error('订单不存在');
            if(!in_array($order['status'],[1,15,16])) return $this->error('该订单不能编辑');
            //判断已有结算信息的订单不能修改散客状态
            $settle_info = CashSettleInfoModel::getById(['order_id'=>$order_id]);
            if($settle_info) return $this->error('有结算信息，不能修改散客状态');
        }
        Db::startTrans();
        try{
            if($open_table_id){
                $ot = OpenTableModel::getById(['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_id]);
                if(empty($ot)) return $this->error('开台不存在');
                //修改开台信息
                OpenTableModel::up(['member_id'=>$member_id],['open_table_id'=>$open_table_id]);
                if($is_fit>-1){
                    if($is_fit){
                        //不是散客变为散客
                        $data['is_fit'] = 1;
                        $data['member_id'] = 0;
                        //修改购物车
                        CartModel::up($data,['open_table_id'=>$open_table_id,'shop_id'=>$this->request->shopId,'origin_type'=>2,'is_delete'=>0]);
                    }else{
                        if($member_id<1) return $this->error('不是散客需要传用户id');
                        $data['is_fit'] = 0;
                        $data['member_id'] = $member_id;
                        //修改购物车
                        CartModel::up($data,['open_table_id'=>$open_table_id,'shop_id'=>$this->request->shopId,'origin_type'=>2,'is_delete'=>0]);
                    }

                }
            }else{
                if($is_fit){
                    //不是散客变成散客
                    //不是散客之前的会员id
                    if($member_id<1) return $this->error('需要传会员id');
                    CartModel::up(['is_fit'=>$is_fit,'member_id'=>0],['member_id'=>$member_id,'table_number_id'=>0,'is_fit'=>0,'shop_id'=>$this->request->shopId,'origin_type'=>2,'is_delete'=>0]);
                }else{
                    //散客变为不是散客
                    //要变成不是散客新的会员id
                    if($member_id<1) return $this->error('需要传会员id');
                    CartModel::up(['is_fit'=>$is_fit,'member_id'=>$member_id],['member_id'=>0,'table_number_id'=>0,'is_fit'=>1,'shop_id'=>$this->request->shopId,'origin_type'=>2,'is_delete'=>0]);
                }
            }

            //推送
            $s_data['data']['table_number_id'] = isset($ot)?$ot['table_number_id']:0;
            $s_data['type'] = 'cart';
            pushWebsocket($this->request->shopId,$this->request->accountId,$s_data);

            Db::commit();

            return $this->success('设置成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
    }

    /**
     *换台（直接点单不能换台）
     */
    public function changeTable(){
        $open_table_id = $this->request->param('open_table_id/d',0);
        $table_number_id = $this->request->param('table_number_id/d',0);

        $opent = OpenTableModel::getById(['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_id]);
        if(empty($opent)) return $this->error('开台不存在');

        $table = TableNumberModel::info(['shop_id'=>$this->request->shopId,'is_effect'=>1,'id'=>$table_number_id]);
        if(empty($table)) return $this->error('桌台不存在');
        $ot = OpenTableModel::getById(['shop_id'=>$this->request->shopId,'table_number_id'=>$table_number_id,'status'=>0]);
        if($ot) return $this->error('桌台已被占用');
        Db::startTrans();
        try{
            $data['table_number_id'] = $table_number_id;
            OpenTableModel::update($data,['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_id]);
            CartModel::up($data,['open_table_id'=>$open_table_id,'shop_id'=>$this->request->shopId,'origin_type'=>2,'is_delete'=>0]);
            
            Db::commit();

            return $this->success('设置成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        $return['open_table_id'] = $open_table_id;
        $return['member_id'] = $opent['member_id'];
        $return['is_fit'] = $opent['is_fit'];
        return $this->success($return);

    }
    /**
     *并台的前提是桌台都要是已开台的才能并台，结账页面金额为并的桌台的所有金额（第一个为主台，后面为次台，有并1并2）
     *联台的前提是桌台都要是已开台的才能联台，在点单页面选择并台结账的话，结账的金额为所有联台的金额，否则只为当前桌台（第一个为主台，后面为次台，有联1联2）
     *并台后，次台的用户改为主台的，并且次台不能修改散客状态
     */
    public function jointTable(){
        $open_table_ids = $this->request->param('open_table_id/a',[]);
        $type = $this->request->param('type/d',1);//1并台2联台

        if(count($open_table_ids)<2) return $this->success('桌台数必须大于等于2');
        //查询当天已有的并台
        $start_time = date('Y-m-d').' 00:00:00';
        $end_time = date('Y-m-d').' 23:59:59';
        $max_num = CashJointTableModel::where(['shop_id'=>$this->request->shopId,'type'=>$type,'is_delete'=>0])
            ->where('add_time','between',[$start_time,$end_time])
            ->order(['num'=>'desc'])
            ->find();

        $data = [];
        Db::startTrans();
        try{
            //主
            $master_open_table = OpenTableModel::where(['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_ids[0],'status'=>0])->find();
            for ($i=0;$i<count($open_table_ids);$i++){
                $open_table = OpenTableModel::where(['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_ids[$i],'status'=>0])->find();
                if(empty($open_table)) return $this->success('有桌台未开台');
                //是否已生成订单
                //是否已被其他桌连台并台
                $have_joint = CashJointTableModel::info(['open_table_id'=>$open_table_ids[$i],'table_number_id'=>$open_table['table_number_id'],'is_delete'=>0]);
                if($have_joint) return $this->success('有桌台已被并台或联台');
                if($i<1){
                    $have_master = CashJointTableModel::info(['master_open_table_id'=>$open_table_ids[$i],'master_table_number_id'=>$master_open_table['table_number_id'],'is_delete'=>0]);
                    if($have_master) return $this->success('主桌台已是主桌台了');
                }
                if($i>0){
                    $data[] = [
                        'shop_id'=>$this->request->shopId,
                        'master_open_table_id'=>$open_table_ids[0],
                        'master_table_number_id'=>$master_open_table['table_number_id'],
                        'open_table_id'=>$open_table_ids[$i],
                        'table_number_id'=>$open_table['table_number_id'],
                        'type'=>$type,
                        'num'=>$max_num + 1,
                        'add_ip'=>request()->ip(),
                    ];
                    //次台用户信息修改为主台的
                    CartModel::up(['member_id'=>$master_open_table['member_id'],'is_fit'=>$master_open_table['is_fit']],['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_ids[$i],'is_delete'=>0]);
                    OpenTableModel::up(['member_id'=>$master_open_table['member_id'],'is_fit'=>$master_open_table['is_fit']],['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_ids[$i],'is_delete'=>0]);
                    $cart_ids = CartModel::where(['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_ids[$i],'is_delete'=>0])->column('cart_id');
                    $where[] = ['cart_id','in',$cart_ids];
                    CartDetailModel::up(['member_id'=>$master_open_table['member_id']],$where);
                }

            }
            $model = new CashJointTableModel();
            $model->saveAll($data);

            Db::commit();

            return $this->success('操作成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }
    /**
     *撤销开台(有联台和并台时，主台点击撤销开台需要先撤销联台和并台才能撤销开台)
     * 如果只有两个桌台并台或者连台的话次台撤销后连台并台就自动取消，大于两个桌台的次台撤销后还有次台的并台和连台继续生效。
     */
    public function revokeOnTable(){
        $open_table_id = $this->request->param('open_table_id/d',0);
        if($open_table_id<1) return $this->error('开台不存在');

        $ot = OpenTableModel::getById(['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_id],'o.*,t.name as table_name,r.name as region_name');
        if(empty($ot)) return $this->error('开台不存在');

        $m_jt = CashJointTableModel::info(['master_open_table_id'=>$open_table_id,'status'=>0,'is_delete'=>0]);
        if($m_jt && $m_jt['type']==1) return $this->error('需要先撤销并台');
        if($m_jt && $m_jt['type']==2) return $this->error('需要先撤销联台');


        $cart = CartModel::list(['open_table_id'=>$open_table_id,'shop_id'=>$this->request->shopId,'is_delete'=>0]);
        if($cart) return $this->error('购物车已有数据不能撤销');

        //直接取消
        OpenTableModel::up(['status'=>1,'is_delete'=>1],['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_id]);

        return $this->success('撤销成功');
    }
    /**
     * 主台撤销联台或开台
     */
    public function revokeJointTable(){
        $open_table_id = $this->request->param('open_table_id/d',0);
        $revoke_open_table_ids = $this->request->param('revoke_open_table_id/a');
        $type = $this->request->param('type/d',1);//1并台2联台
        if($open_table_id<1) return $this->error('开台不存在');

        $ot = OpenTableModel::getById(['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_id],'o.*,t.name as table_name,r.name as region_name');
        if(empty($ot)) return $this->error('开台不存在');

        //是否有为主台的联台或并台
        $master = CashJointTableModel::info(['master_open_table_id'=>$open_table_id,'status'=>0,'is_delete'=>0,'type'=>$type]);
        if(empty($master)) return $this->error('不是主台');
        //撤销
        $where[] = ['master_open_table_id','=',$open_table_id];
        $where[] = ['status','=',0];
        $where[] = ['type','=',$type];
        $where[] = ['is_delete','=',0];
        $where[] = ['open_table_id','In',$revoke_open_table_ids];
        CashJointTableModel::up(['is_delete'=>1],$where);

        return $this->success('撤销成功');
    }
    /**
     * 联台并台结账
     */
    public function liantaiOrder(){
        $open_table_id = $this->request->param('open_table_id/d',0);
        if($open_table_id<1) return $this->error('开台不存在');

        $ot = OpenTableModel::getById(['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_id,'status'=>0],'o.*,t.name as table_name,r.name as region_name');
        if(empty($ot)) return $this->error('开台不存在');

        CashJointTableModel::up(['is_joint_order'=>1],['shop_id'=>$this->request->shopId,'master_open_table_id'=>$open_table_id,'type'=>2,'status'=>0,'is_delete'=>0]);
        CashJointTableModel::up(['is_joint_order'=>1],['shop_id'=>$this->request->shopId,'open_table_id'=>$open_table_id,'type'=>2,'status'=>0,'is_delete'=>0]);

        return $this->success('操作成功');
    }
}

